package com.zq.im;


import android.content.Intent;
import android.widget.EditText;
import android.widget.Toast;

import com.gyf.immersionbar.ImmersionBar;
import com.zq.im.api.UserApi;
import com.zq.im.bean.BaseModel;
import com.zq.im.bean.LoginBean;
import com.zq.im.bean.User;
import com.zq.im.retrofit.BaseCallBack;
import com.zq.im.retrofit.RetrofitManager;
import com.zq.im.utils.SharePreferenceUtils;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.Call;

public class LoginActivity extends BaseActivity {

    @BindView(R.id.account)
    EditText account;

    @BindView(R.id.password)
    EditText password;
    private String mAction;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();
        ImmersionBar.with(this)
                .statusBarDarkFont(true)
                .statusBarColor(R.color.white)
                .init();
    }

    @Override
    protected void initData() {
        super.initData();
        Intent intent = getIntent();
        mAction = intent.getStringExtra("action");
    }

    /**
     * 登录
     */
    @OnClick(R.id.login)
    void login() {

        String accountStr = account.getText().toString();
        if (accountStr.length() == 0) {
            Toast.makeText(mActivity, "请输入账号", Toast.LENGTH_SHORT).show();
            return;
        }
        String passwordStr = password.getText().toString();
        if (passwordStr.length() == 0) {
            Toast.makeText(mActivity, "请输入密码", Toast.LENGTH_SHORT).show();
            return;
        }
        User user = new User().setPassword(passwordStr).setUsername(accountStr);
        UserApi userApi = RetrofitManager.getRetrofit().create(UserApi.class);
        Call<BaseModel<LoginBean>> login = userApi.login(user);

        login.enqueue(new BaseCallBack<LoginBean>() {

            @Override
            public void onSuccess(LoginBean loginBean) {
                Toast.makeText(mActivity, "登录成功", Toast.LENGTH_SHORT).show();
                //保存token
                SharePreferenceUtils.putString("token", loginBean.getToken());
                SharePreferenceUtils.putString("userId", loginBean.getUserId());
                SharePreferenceUtils.putString("account", accountStr);

                if (mAction != null && mAction.equals("token_expire")) {
                    finish();
                } else {
                    startActivity(new Intent(LoginActivity.this, MainActivity.class));
                    finish();
                }
            }

            @Override
            public void onFailure(Throwable t) {
                Toast.makeText(mActivity, "登录失败", Toast.LENGTH_SHORT).show();
            }
        });


    }


    /**
     * 注册
     */
    @OnClick(R.id.register)
    void register() {
        startActivity(new Intent(this, RegisterActivity.class));
    }


}